/*
 * key.c
 *
 *  Created on: Jul 3, 2020
 *      Author: HYJ
 */

#include "key.h"

u8 KEY_Scan(struct KEY_COMMON *this) {
	if (this->mode == L_PRES_DISABLE) {				//支持连按,不支持长按
		for (int i = 0; i < this->pin_count; i++) {
			if (this->pin[i].GPIO_InitStruct.Pull == GPIO_PULLUP) {
				if (!this->pin[i].ReadPin(&this->pin[i])) {
					return (i + 1);
				}
			} else if (this->pin[i].GPIO_InitStruct.Pull == GPIO_PULLDOWN) {
				if (this->pin[i].ReadPin(&this->pin[i])) {
					return (i + 1);
				}
			}
		}
	} else {												//不支持连按（支持长按，检测按住按键的时间）
		for (int i = 0; i < this->pin_count; i++) {
			if (this->pin[i].GPIO_InitStruct.Pull == GPIO_PULLUP) {
				if (!this->pin[i].ReadPin(&this->pin[i])) {
					while (!this->pin[i].ReadPin(&this->pin[i])) {
						HAL_Delay(10);
						this->press_time++;
						if (this->press_time > 10000) {
							return (i + 1);
						}
					}
					return (i + 1);
				}
			} else if (this->pin[i].GPIO_InitStruct.Pull == GPIO_PULLDOWN) {
				if (this->pin[i].ReadPin(&this->pin[i])) {
					while (this->pin[i].ReadPin(&this->pin[i])) {
						HAL_Delay(10);
						this->press_time++;
						if (this->press_time > 10000) {
							return (i + 1);
						}
					}
					return (i + 1);
				}
			}
		}
	}
	return 0;
}

void KEY_Add_New_Key(struct KEY_COMMON *this, GPIO_TypeDef *port, uint32_t pin) {
	this->pin_count++;
	GPIO_COMMON *p = (GPIO_COMMON*) malloc(this->pin_count * sizeof(GPIO_COMMON));
	for (int i = 0; i < this->pin_count; i++) {
		p[i] = this->pin[i];
	}
	free(this->pin);
	this->pin = p;
	GPIO_COMMON *key_pin = new_Gpio(key_pin, port, pin, GPIO_MODE_INPUT,	this->pull,GPIO_SPEED_FREQ_HIGH);
	this->pin[this->pin_count - 1] = *key_pin;
}

KEY_COMMON* new_Key(struct KEY_COMMON *this, GPIO_TypeDef *port, uint32_t pin,
		uint32_t pull, uint8_t mode) {
	this = (struct KEY_COMMON*) calloc(1, sizeof(struct KEY_COMMON));
	this->pull = pull;
	this->mode = mode;
	this->pin_count = 0;
	this->press_time = 0;
	this->append = KEY_Add_New_Key;
	this->Scan=KEY_Scan;
	this->append(this,port, pin);
	return this;
}
